<!--
 @description 文件上传
 @fileName CUpload.vue
 @author zengqiongying
 @created 2021/10/22 11:09:33
-->
<template>
  <div>
    <template v-if="!hideImg&&(imageUrl || privateImageUrl)">
      <div v-if="['image','video','audio'].includes(fileType)" :style="viewStyle">
        <img v-if="fileType==='image'" :src="imageUrl || privateImageUrl" class="file-cover-box" :style="viewStyle">
        <video v-else-if="fileType ==='video'" :src="imageUrl || privateImageUrl" class="file-cover-box" controls="controls" :style="viewStyle">
          您的浏览器不支持 video 标签。
        </video>
        <div v-else-if="fileType ==='audio'" class="flex-box file-cover-box">
          <audio :src=" imageUrl || privateImageUrl" controls="controls" style="height:24px" :style="viewStyle">
            您的浏览器不支持 audio 标签。
          </audio>
        </div>
      </div>
      <div v-else style="width:100%; line-height:22px">
        <a :href="imageUrl || privateImageUrl" target="_blank">{{ privateImageName }}</a>
      </div>
      <div class="btn-del-file" @click.stop="handleBeforeRemove"><i class="el-icon-delete" />删除</div>
    </template>
    <el-upload
      v-else
      ref="uploadRef"
      class="qup-img-uploader el-upload-list--picture-card"
      :style="{height:sizeStyle.height}"
      auto-upload
      with-credentials
      :name="name"
      :data="data"
      :headers="headers"
      :action="action"
      :on-change="handleChange"
      :disabled="uploadDisabled"
      :on-error="handleUploadError"
      :on-progress="handleProgress"
      :on-success="handleUploadSuccess"
      :before-upload="handleBeforeUpload"
      :multiple="multiple"
      :limit="limit"
      :show-file-list="false"
      :on-exceed="handleExceed"
    >
      <!-- :file-list="fileList" -->
      <!-- <div v-if="!hideImg&&(imageUrl || privateImageUrl)" :style="sizeStyle">
        <img v-if="fileType==='image'" :src="imageUrl ? imageUrl : privateImageUrl" class="file-cover-box">
        <video v-else-if="fileType ==='video'" :src="imageUrl ? imageUrl : privateImageUrl" class="file-cover-box" controls="controls">
          您的浏览器不支持 video 标签。
        </video>
        <div v-else-if="fileType ==='audio'" class="flex-box file-cover-box">
          <audio :src="imageUrl ? imageUrl : privateImageUrl" controls="controls" style="height:30px">
            您的浏览器不支持 audio 标签。
          </audio>
        </div>
        <div v-else>
          <a :href="imageUrl ? imageUrl : privateImageUrl" target="_blank">{{ privateImageName }}</a>
        </div>
      </div> -->
      <template v-if="!imageUrl && !uploadPercentage">
        <el-button size="small" type="primary">{{ btnTxt }}</el-button>
      </template>
      <el-progress
        v-else
        type="line"
        :percentage="uploadPercentage"
        :status="uploadStatus || null"
        style="width:400px"
        :text-inside="true"
        :stroke-width="26"
      />
      <span v-if="cancelStatus" class="el-upload-list__item-actions" @click.stop="cancelUploadFile"><i class="el-icon-close" /></span>
      <span v-if="clearStatus" class="el-upload-list__item-actions" @click.stop="clearUploadStatus"><i class="el-icon-close" /></span>

      <span
        v-if="mask && (imageUrl || privateImageUrl)"
        class="el-upload-list__item-actions"
        :style="{borderRadius:sizeStyle.borderRadius}"
        @click="maskClick"
      >
        <span
          v-if="!uploadDisabled && deleteIcon"
          @click.stop="handleBeforeRemove"
        >
          <i class="el-icon-delete" />
        </span>
        <slot name="mask-btn" />
      </span>
    </el-upload>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
export default {
  name: 'CUpload',
  props: {
    acceptType: {
      type: Array,
      default: () => []
    }, // new Array("avi","wmv","mpg","mpeg","mov","rm","ram","swf","flv","mp4","mp3","wma","avi","rm","rmvb","flv","mpg","mkv")
    // 视频：mp4、mkv、mov、flv、rmvb、avi、wmv、m4v
    // 音频：mp3、wma、wav、amr、m4a
    // 图片：jpg,png,jpeg
    fileType: {
      type: String,
      default: 'image' // picture  video audio file
    },
    btnTxt: {
      type: String,
      default: '点击上传'
    },
    data: {
      type: Object,
      default() {
        return {}
      }
    },
    action: {
      type: String,
      default: () => `${process.env.VUE_APP_BASE_API}/api/v1/file/upload` // 附件默认上传路径
    },
    name: {
      type: String,
      default: 'multipartFile'
    },
    imageSize: {
      type: Number,
      default: 10
    },
    uiType: {
      // 文件上传框风格 circle / rectangle
      type: String,
      required: false,
      default: 'rectangle'
    },
    width: {
      // 文件上传框高度, 若是圆形则取宽度作为直径
      type: Number,
      default: 158
    },
    height: {
      type: Number,
      default: 83
    },
    isView: {
      type: Boolean,
      default: true
    }, // 是否预览
    viewWidth: {
      type: Number,
      default: 158
    }, // 预览高度
    viewHeight: {
      type: Number,
      default: 83
    }, // 预览宽度
    limit: {
      type: Number,
      default: 1
    },
    mask: Boolean, // 是否显示遮罩，true表示在有图片的时候显示遮罩，可在遮罩上添加各种按钮,默认有删除按钮
    stopDefaultFileDialog: { // 是否在点击遮罩非按钮区域时阻止事件冒泡，防止打开文件选择框
      type: Boolean,
      default: true
    },
    deleteIcon: {
      type: Boolean,
      default: true
    },
    multiple: {
      type: Boolean,
      default: false
    },
    imageUrl: {
      type: String,
      default: ''
    },
    disabled: Boolean,
    beforeUpload: {
      type: Function,
      default: function() {
        return true
      }
    },
    beforeRemove: {
      type: Function,
      default: function() {
        return true
      }
    }
  },
  inject: { // 获取父组件的provide
    elForm: { default: '' },
    elFormItem: { default: '' }
  },
  data() {
    return {
      headers: {
        // 文件上传请求头
        // Authorization: linkToken.getLocalToken()
        'X-Token': this.$store.getters.token ? getToken() : '',
        'Authorization': this.$store.getters.token ? 'Bearer ' + getToken() : ''
      },
      sizeStyle: {

      },
      progressStyle: { margin: '10px 10px' }, // 进度框样式
      progressWidth: 50, // 进度框宽度 --直径
      privateImageUrl: this.imageUrl, // 图片路径，privateImageUrl 为组件内图片变量，优先取父组件传入的图片变量，无则使用此路径变量，防止父组件上传图片后没有设置imageUrl
      privateImageName: this.imageUrl,
      uploadPercentage: 0, // 上传百分比
      uploadStatus: '', // 上传是否失败，失败时会设置为 exception
      CIRCLE: 'circle',
      RECTANGLE: 'rectangle',
      cancelStatus: false, // 是否需要取消上传
      clearStatus: false, // 是否可以清除组件上传状态
      fileList: [
        // { name: '', url: '' }
      ],
      loading: null
    }
  },
  computed: {
    uploadDisabled() {
      return this.disabled || (this.elForm || {}).disabled // 通过上层表单元素是否禁用来确定当前是否禁用
    },
    viewStyle() {
      const styl = {}
      if (this.viewHeight) {
        styl.height = `${this.viewHeight}px`
      }
      if (this.viewWidth) {
        styl.width = `${this.viewWidth}px`
      }
      return { ...this.sizeStyle, ...styl }
    }
  },
  watch: {
    imageUrl: function(val) {
      this.privateImageUrl = val // 外部修改触发内部更新，但内部更新不完全依赖外部
      if (!this.fileType) {
        this.privateImageName = val
      } else {
        this.privateImageName = ''
      }
    },
    fileType(newVal, oldVal) {
      this.setAreaStyle()
    }
  },
  created: function() {
    this.setAreaStyle()
  },
  methods: {
    setAreaStyle() {
      if (this.uiType === this.CIRCLE) {
      // 圆形
        this.sizeStyle.height = this.width + 'px'
        this.sizeStyle.width = this.width + 'px'
        this.sizeStyle.borderRadius = this.width / 2 + 'px'
        this.sizeStyle.lineHeight = this.width + 'px'
        if (this.width < 100) {
          this.progressWidth = this.width - 10
          this.progressStyle.margin = '5px'
        } else {
          this.progressWidth = this.width >> 1
          this.progressStyle.margin = (this.width >> 2) + 'px'
        }
      } else if (this.uiType === this.RECTANGLE) {
      // 矩形
        this.sizeStyle.height = this.height + 'px'
        this.sizeStyle.width = this.width + 'px'
        this.sizeStyle.lineHeight = this.height + 'px'

        /** 计算进度框大小位置 */
        var d = (this.width > this.height ? this.height : this.width) - 20 // 直径 最小50才行, 所以宽高必须70
        var marginTop = (this.height - d) / 2
        var marginLeft = (this.width - d) / 2
        marginTop = marginTop > 0 ? marginTop : 0
        marginLeft = marginLeft > 0 ? marginLeft : 0
        this.progressWidth = d
        this.progressStyle.margin = marginTop + 'px ' + marginLeft + 'px'
      }
      if (!this.fileType) {
        this.sizeStyle.height = this.height + 'px'
        this.sizeStyle.width = '100%'
        this.sizeStyle.lineHeight = '24px'
      }
    },
    refreshHeaders() {
      this.headers = {
        'X-Token': this.$store.getters.token ? getToken() : '',
        'Authorization': this.$store.getters.token ? 'Bearer ' + getToken() : ''
      }
    },
    handleBeforeUpload: function(file) {
      this.refreshHeaders()
      // 上传前校验
      let isFormat = true
      let formatError = '文件上传格式有误!'
      if (this.fileType && ['image', 'video', 'audio'].includes(this.fileType)) {
        isFormat = file.type.indexOf(`${this.fileType}/`) > -1
        if (!isFormat) {
          const tmpObj = {
            'image': '只能上传图片格式',
            'video': '只能上传视频格式',
            'audio': '只能上传音频格式'
          }
          formatError = `${formatError},${tmpObj[this.fileType]}。`
        }
      } else {
        // isFormat = file.type.indexOf(`image/`) === -1 && file.type.indexOf(`video/`) === -1 && file.type.indexOf(`audio/`) === -1
        // formatError = `${formatError},不能上传图片、视频、音频格式。`
      }
      if (!isFormat) {
        this.$message.error(formatError)
      }
      var isLt2M = file.size / 1024 / 1024 < this.imageSize
      if (!isLt2M) {
        this.$message.error('上传大小不能超过 ' + this.imageSize + 'M!')
      }
      if (isFormat && isLt2M) {
        this.loading = this.$loading({
          lock: true,
          text: '正在上传...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        return this.beforeUpload(file)
      } else {
        return false
      }
    },
    handleExceed(files, fileList) {
      this.$message.error(`当前最多只允许上传${this.limit}个文件，本次选择了 ${files.length} 个`)
    },
    handleUploadSuccess(response, file) {
      // 上传成功回调
      this.loading && this.loading.close()
      this.cancelStatus = false // 隐藏取消按钮
      if (response.success === 1) {
        const privateImageUrl = URL.createObjectURL(file.raw)
        this.uploadPercentage = 0// 上传进度归零, 隐藏进度框
        const fileData = {
          fileSize: Math.round((file.size / 1024) * 10) / 10,
          sourceFileName: file.name,
          sourceFileUrl: privateImageUrl// 返回本地图片路径，不要取服务器返回对象的attachmentPath,会导致重新加载
        }
        this.$emit('upload-success', { ...fileData, ...response.data })

        if (this.isView) {
          this.privateImageUrl = privateImageUrl
          if (!this.fileType) {
            this.privateImageName = file.name
          }
        }
      } else {
        if (response.code === 401 || response.code === '401' || response.status === 401) {
          this.refreshToken({}, () => {
            this.refreshHeaders()
          })
        } else {
          this.$message.error('上传失败: ' + response.msg)
          this.uploadStatus = 'exception'
          this.clearStatus = true
        }
        this.$refs.uploadRef.clearFiles()
      }
      this.$emit('upload-finish', response)
    },
    handleProgress(event, file) {
      this.cancelStatus = true // 展示中断按钮
      // 上传中 event.percent 百分比
      // this.$emit('before-upload',file);//上传之前清空之前的图片url
      this.uploadStatus = '' // 上传状态置空,
      this.uploadPercentage = parseFloat(event.percent.toFixed(1))
      if (this.uploadPercentage > 99) {
        this.uploadPercentage = 99.0
      }
      this.privateImageUrl = ''
    },
    handleUploadError(err, file) {
      // 上传失败
      this.loading && this.loading.close()
      const res = JSON.parse(JSON.stringify(err))
      if (res.code === 401 || res.code === '401' || res.status === 401) {
        this.refreshToken({}, () => {
          this.refreshHeaders()
        })
      } else {
        this.$message.error('上传失败: ' + err)
        // console.log('上传失败', JSON.stringify(err))
        this.uploadStatus = 'exception'
        this.clearStatus = true
      }
      this.$refs.uploadRef.clearFiles()
    },
    clearUploadStatus() {
      this.uploadPercentage = 0
      this.clearStatus = false
    },
    cancelUploadFile() {
      this.$refs.uploadRef.abort()
      this.uploadPercentage = 0
      this.$message({
        type: 'success',
        message: '上传已中断,请重新上传图片'
      })
      this.cancelStatus = false
    },
    handleChange: function(file) {
      this.$emit('on-change', '')
    },
    handleBeforeRemove: function(file) {
      const before = this.beforeRemove()
      if (before && before.then) {
        before.then(
          () => {
            this.onRemove()
          })// 注意箭头函数作用域
      } else if (before !== false) {
        this.onRemove()
      }
    },

    /** 清除显示图片 */
    onRemove: function() {
      this.privateImageUrl = ''
      this.imageUrl = ''
      this.$emit('remove') // 点击删除
    },
    maskClick(event) {
      // 阻止默认的文件弹出框
      if (this.stopDefaultFileDialog) {
        event.stopImmediatePropagation()
      }
    }
  }
}
</script>
<style lang='scss' scoped>
.file-cover-box{
  background:#cccccc;
  object-fit: cover;
}
.flex-box{
  display: flex;
  align-items: center;
  justify-content: center;
}
.btn-del-file{
  margin: 10px;
  width:60px;
  color:#999;
  text-align: center;
  cursor: pointer;
  .el-icon-delete{
    font-size: 14px;
    margin-right: 5px;
  }
}
.qup-img-uploader{
    position: relative;
    display: inline-block;
  }
  .qup-img-uploader .uploader-border{
    border: 1px dashed rgb(217, 217, 217);
    font-size: 24px;
    color: #8c939d;
  }
  .qup-img-uploader .uploader-border:hover{
    border-color:#409EFF;
  }
  .qup-img-uploader .el-upload-list__item-actions:hover {
    opacity: 1;
  }
  .qup-img-uploader .el-upload-list__item-actions {
    position: absolute;
    width: 100%;
    height: 100%;
    left: 0;
    top: 0;
    cursor: default;
    text-align: center;
    color: #fff;
    opacity: 0;
    font-size: 20px;
    background-color: rgba(0, 0, 0, .5);
    -webkit-transition: opacity .3s;
    transition: opacity .3s;
  }
  .qup-img-uploader .el-upload-list__item-actions span {
    display: none;
    cursor: pointer;
  }
  .qup-img-uploader .el-upload-list__item-actions:hover span {
    display: inline-block;
  }
  .qup-img-uploader .el-upload-list__item-actions span + span {
    margin-left: 15px;
  }

  /* 覆盖原样式 */
  .qup-img-uploader .el-progress {
    top: unset;
    left: unset;
    -webkit-transform: unset;
    transition: unset;
    bottom: unset;
    width: unset;
  }
  /** 单图片上传组件样式END */
</style>
